package com.zhentao.controller;

import com.zhentao.annotation.OperationLog;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/abnormalDataExplanation")
@CrossOrigin
public class abnormalDataExplanationController {

    @Autowired
    private DataExceptionService dataExceptionService;
    
    @Autowired
    private DataCollectionService dataCollectionService;
    
    @Autowired
    private CustomsDataLogService customsDataLogService;

    /**
     * 获取异常数据列表
     */
    @OperationLog(bizModule = 2, bizType = 5, description = "查询异常数据列表", recordParams = false)
    @GetMapping("/list")
    public Map<String, Object> getExceptionList(@RequestParam(defaultValue = "1") Integer page,
                                              @RequestParam(defaultValue = "10") Integer size,
                                              @RequestParam(required = false) Integer exceptionType,
                                              @RequestParam(required = false) Integer handleStatus) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 构建查询条件
            Map<String, Object> queryParams = new HashMap<>();
            if (exceptionType != null) {
                queryParams.put("exceptionType", exceptionType);
            }
            if (handleStatus != null) {
                queryParams.put("handleStatus", handleStatus);
            }
            
            // 分页查询异常数据
            List<DataException> exceptionList = dataExceptionService.getPageList(page, size, queryParams);
            
            // 关联查询采集数据信息
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (DataException exception : exceptionList) {
                Map<String, Object> item = new HashMap<>();
                item.put("exception", exception);
                
                // 获取关联的采集数据
                if (exception.getCollectionId() != null) {
                    DataCollection collection = dataCollectionService.getById(exception.getCollectionId());
                    item.put("collection", collection);
                }
                
                resultList.add(item);
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", resultList);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取异常数据详情
     */
    @OperationLog(bizModule = 2, bizType = 5, description = "查询异常数据详情")
    @GetMapping("/detail/{id}")
    public Map<String, Object> getExceptionDetail(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            DataException exception = dataExceptionService.getById(id);
            if (exception == null) {
                result.put("code", 404);
                result.put("message", "异常数据不存在");
                return result;
            }
            
            Map<String, Object> data = new HashMap<>();
            data.put("exception", exception);
            
            // 获取关联的采集数据
            if (exception.getCollectionId() != null) {
                DataCollection collection = dataCollectionService.getById(exception.getCollectionId());
                data.put("collection", collection);
            }
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", data);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 处理异常数据
     */
    @OperationLog(bizModule = 2, bizType = 4, description = "处理异常数据")
    @PostMapping("/handle")
    public Map<String, Object> handleException(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer exceptionId = (Integer) params.get("exceptionId");
            Integer handleStatus = (Integer) params.get("handleStatus"); // 1-未处理 2-已修复 3-忽略
            Integer userId = (Integer) params.get("userId");
            String handleRemark = (String) params.get("handleRemark");
            
            DataException exception = dataExceptionService.getById(exceptionId);
            if (exception == null) {
                result.put("code", 404);
                result.put("message", "异常数据不存在");
                return result;
            }
            
            // 更新异常处理状态
            exception.setHandleStatus(handleStatus);
            exception.setHandleTime(new Date());
            
            boolean success = dataExceptionService.updateById(exception);
            
            if (success) {
                // 如果是已修复状态，同时更新关联的采集数据状态
                if (handleStatus == 2 && exception.getCollectionId() != null) {
                    DataCollection collection = dataCollectionService.getById(exception.getCollectionId());
                    if (collection != null && collection.getStatus() == 3) { // 异常状态
                        collection.setStatus(1); // 改为待入库
                        dataCollectionService.updateById(collection);
                    }
                }
                
                result.put("code", 200);
                result.put("message", "异常数据处理成功");
                result.put("data", exception);
            } else {
                result.put("code", 500);
                result.put("message", "异常数据处理失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量处理异常数据
     */
    @OperationLog(bizModule = 2, bizType = 4, description = "批量处理异常数据")
    @PostMapping("/batchHandle")
    public Map<String, Object> batchHandleException(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Integer> exceptionIds = (List<Integer>) params.get("exceptionIds");
            Integer handleStatus = (Integer) params.get("handleStatus");
            Integer userId = (Integer) params.get("userId");
            
            if (exceptionIds == null || exceptionIds.isEmpty()) {
                result.put("code", 400);
                result.put("message", "请选择要处理的异常数据");
                return result;
            }
            
            int successCount = 0;
            for (Integer exceptionId : exceptionIds) {
                DataException exception = dataExceptionService.getById(exceptionId);
                if (exception != null) {
                    exception.setHandleStatus(handleStatus);
                    exception.setHandleTime(new Date());
                    
                    if (dataExceptionService.updateById(exception)) {
                        successCount++;
                        
                        // 如果是已修复状态，同时更新关联的采集数据状态
                        if (handleStatus == 2 && exception.getCollectionId() != null) {
                            DataCollection collection = dataCollectionService.getById(exception.getCollectionId());
                            if (collection != null && collection.getStatus() == 3) {
                                collection.setStatus(1);
                                dataCollectionService.updateById(collection);
                            }
                        }
                    }
                }
            }
            
            result.put("code", 200);
            result.put("message", "批量处理完成，成功处理" + successCount + "条异常数据");
            result.put("data", successCount);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 创建异常数据记录
     */
    @OperationLog(bizModule = 2, bizType = 3, description = "创建异常数据记录")
    @PostMapping("/create")
    public Map<String, Object> createException(@RequestBody DataException dataException) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 设置默认值
            dataException.setHandleStatus(1); // 未处理
            
            boolean success = dataExceptionService.save(dataException);
            
            if (success) {
                // 同时更新关联采集数据的状态为异常
                if (dataException.getCollectionId() != null) {
                    DataCollection collection = dataCollectionService.getById(dataException.getCollectionId());
                    if (collection != null) {
                        collection.setStatus(3); // 异常状态
                        dataCollectionService.updateById(collection);
                    }
                }
                
                result.put("code", 200);
                result.put("message", "异常数据记录创建成功");
                result.put("data", dataException);
            } else {
                result.put("code", 500);
                result.put("message", "异常数据记录创建失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取异常统计信息
     */
    @OperationLog(bizModule = 2, bizType = 7, description = "获取异常统计信息", recordParams = false)
    @GetMapping("/statistics")
    public Map<String, Object> getExceptionStatistics() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 按异常类型统计
            Map<String, Object> typeStats = new HashMap<>();
            typeStats.put("formatError", dataExceptionService.countByType(1)); // 格式错误
            typeStats.put("fieldMissing", dataExceptionService.countByType(2)); // 字段缺失
            typeStats.put("logicConflict", dataExceptionService.countByType(3)); // 逻辑冲突
            
            // 按处理状态统计
            Map<String, Object> statusStats = new HashMap<>();
            statusStats.put("unhandled", dataExceptionService.countByStatus(1)); // 未处理
            statusStats.put("fixed", dataExceptionService.countByStatus(2)); // 已修复
            statusStats.put("ignored", dataExceptionService.countByStatus(3)); // 忽略
            
            statistics.put("typeStatistics", typeStats);
            statistics.put("statusStatistics", statusStats);
            
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", statistics);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
        }
        return result;
    }
}
